package com.cnap.model.validator;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ArrayUtil;
import com.cnap.model.application.ValidInterface;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

/**
 * 枚举校验器
 *
 * @author xc
 **/
public class EnumValidator implements ConstraintValidator<EnumCheck, String> {

    private Class<?> enumClass;

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (Objects.isNull(s) || CharSequenceUtil.isEmpty(s)) {
            return true;
        }
        if (Objects.isNull(enumClass)) {
            return true;
        }
        ValidInterface[] enums = (ValidInterface[]) enumClass.getEnumConstants();
        if (ArrayUtil.isEmpty(enums)) {
            return false;
        }
        return enums[0].isValid(s);
    }

    @Override
    public void initialize(EnumCheck constraintAnnotation) {
        enumClass = constraintAnnotation.enumClass();
    }
}
